package fr.generali.accueilclient.gwt.client.controller;

import java.util.HashSet;
import java.util.Set;

import com.google.web.bindery.event.shared.EventBus;

public abstract class AbstractParentController extends AbstractController implements ParentController {
    
    private final Set<Controller> subControllers = new HashSet<Controller>();

    public void register(Controller childController, EventBus eventBus) {
        if (this.subControllers.contains(childController)) {
            throw new IllegalStateException("Controller already added");
        }

        this.subControllers.add(childController);

        childController.startup(eventBus);
    }

    public boolean unregister(Controller childController) {
        if (childController == null) {
            throw new NullPointerException("Child Controller is Null");
        }

        boolean removed =  this.subControllers.remove(childController);
        
        if (removed) {
            childController.shutdown();    
        }
        

        return removed;
    }

    public void shutdown() {
        if (!isStopped()) {
            for (Controller subController : subControllers) {
                subController.shutdown();
            }
            
            subControllers.clear();
        }
        super.shutdown();
    }
}
